package ui;
import java.util.Vector;

import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Command;
import agent.*;

public class ReceiveAgentScreen extends Form implements CommandListener {
	private manager.AgentManagerMIDlet midlet;
	private MeetingAgent agent;
	private Display display;
    private ChoiceGroup cgAgentTimes;
    private Command confirmCommand;
    private Command exitCommand;
	
	public ReceiveAgentScreen(manager.AgentManagerMIDlet midlet,
								Display display,
								MeetingAgent agent){
		super("Please pick the times that suit you");
		this.midlet = midlet;
		this.display = display;
		this.agent = agent;
        cgAgentTimes = new ChoiceGroup("Which times are you available ? ", Choice.MULTIPLE);
        for(int i = 0 ; i < agent.sizeOfStartTimes(); i++){
        	cgAgentTimes.append("Starts at : " + agent.getStartTimes(i) +
        			"and finishes at : " +agent.getFinishTimes(i), null);
        }
        confirmCommand = new Command("Confirm", Command.SCREEN,1);
        exitCommand = new Command("Exit", Command.EXIT, 1);
        this.addCommand(exitCommand);
        this.addCommand(confirmCommand);
        this.append(cgAgentTimes);
        this.setCommandListener(this);
	}
	
	
	public void commandAction(Command c, Displayable d){
		if(c==exitCommand){
			midlet.exitRequested();
		}else if (c==confirmCommand){
			boolean choices[] = new boolean[agent.sizeOfStartTimes()];
			for(int i = 0 ; i < choices.length ; i++){
				choices[i] = cgAgentTimes.isSelected(i);
			}
			//set available times in agent
			int currentContactIndex = agent.getNextIndex();
			if(currentContactIndex==-1)
				System.err.println("Error, next index cannot be found.");
			System.out.println("currentContactIndex is : " + currentContactIndex);
			for(int i = 1 ; i < (choices.length+1);i++){
				if(choices[(i-1)]){
					System.out.println("i is : " + i);
					agent.addAvailableTime(currentContactIndex, i);
				}
			}
			//Set field to true to indicate that this has been visited.
			agent.addAvailableTime(currentContactIndex, 0);
			
			midlet.getIOHandlerManager().sendAgent(agent);
			//IdleScreen idleScreen = new IdleScreen(midlet,display);
			midlet.getUIHandlerManager().setIdleScreen();
		}
	}
}
